package xyz.kongbai121.drawingbed.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import xyz.kongbai121.drawingbed.entity.ImageEntity;
import xyz.kongbai121.drawingbed.service.ImageService;
import xyz.kongbai121.drawingbed.utils.PageUtils;
import xyz.kongbai121.drawingbed.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 *  处理图片信息
 *
 * @author kongbai121
 * @date 2021-10-28 15:21:38
 */
@Slf4j
@RestController
@Api(tags = "图片控制器")
@RequestMapping("/api/image")
@ConfigurationProperties(prefix = "drawing-bed.image")
public class ImageController {

    @Setter @Getter
    private String RequestPrefix;

    @Setter @Getter
    private String filePath;

    @Setter @Getter
    private String host;

    @Autowired
    private ImageService imageService;

    /**
     * 列表
     */
    @ApiOperation(value = "列表", notes = "")
    @GetMapping("/list")
    public R list(@ApiParam(value = "当前页码", required=false) @RequestParam(value = "curPage",required = false) String curPage,
                  @ApiParam(value = "每页显示条数", required=false) @RequestParam(value = "limit",required = false) String limit,
                  @ApiParam(value = "标题", required=false) @RequestParam(value = "name",required = false) String name,
                  @ApiParam(value = "月份(yyyy-MM格式)", required=false) @RequestParam(value = "month",required = false) String month,
                  @ApiParam(value = "token", required=true) @RequestParam("token") String token){
        HashMap<String, Object> params = new HashMap<>();
        params.put("page", curPage);
        params.put("limit", limit);
        params.put("name", name);
        params.put("month", month);
        PageUtils page = imageService.queryPage(params);

        return R.ok().setData(page);
    }


    /**
     * 信息
     */
    @ApiOperation(value = "详情", notes = "")
    @GetMapping("/info/{id}")
    public R info(@ApiParam(value = "id", example = "0", required=true) @PathVariable("id") Long id,
                  @ApiParam(value = "token", required=true) @RequestParam("token") String token){
		ImageEntity image = imageService.getById(id);

        return R.ok().setData(image);
    }

    /**
     * 保存
     */
    @ApiOperation(value = "保存", notes = "")
    @PostMapping("/save")
    public R save(@ApiParam(value = "文件", required=true) @RequestParam("file") MultipartFile file,
                  @ApiParam(value = "名字", required=true) @RequestParam("name") String name,
                  @ApiParam(value = "token", required=true) @RequestParam("token") String token,
                  @ApiParam(value = "与前端无关", required=false) HttpServletRequest req){

        if (file ==null || file.getSize()<=0 || StringUtils.isBlank(file.getOriginalFilename())){
            return R.error("请勿上传空文件!");
        }

        Date date = new Date();

        //文件保存逻辑
        String orgFileName = file.getOriginalFilename();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        String folderName = filePath + simpleDateFormat.format(date);
        File folder = new File(folderName);
        if (!folder.exists() || !folder.isDirectory()){
            boolean mkdir = folder.mkdir();
        }

        // 服务器文件名
        String serverFileName = UUID.randomUUID().toString() + orgFileName.substring(orgFileName.lastIndexOf("."));
        // 文件路径
        String serverFile = folderName + "/" + serverFileName;
        File co = new File(serverFile);
        try {
            Files.copy(file.getInputStream(),co.toPath());
        } catch (IOException e) {
            e.printStackTrace();
            return R.error(4444,"文件保存失败");
        }

        //图片网络路径
        String src = host + RequestPrefix + simpleDateFormat.format(date)+ "/" + serverFileName;
        //保存数据库
        ImageEntity entity = new ImageEntity();
        entity.setName(name);
        entity.setSrc(src);
        entity.setTime(date);
        imageService.save(entity);
        return R.ok().setData(src);
    }

    /**
     * 修改
     */
//    @PutMapping("/update")
    public R update(@RequestBody ImageEntity image){
		imageService.updateById(image);

        return R.ok();
    }

    /**
     * 删除
     */
    @ApiOperation(value = "删除", notes = "")
    @DeleteMapping("/delete/{id}")
    public R delete(@ApiParam(value = "id", example = "0", required=true) @PathVariable("id") Long id,
                    @ApiParam(value = "token", required=true) @RequestParam("token") String token){
		imageService.delele(id);
        return R.ok();
    }

}
